package com.example.itensyuan0609.util;

import com.example.itensyuan0609.bin.MyBean;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
    /*
     * 连接网络
     *
     * */
    public MyBean connetServer() throws IOException {
        //http://v.juhe.cn/toutiao/index?key=d988c64f445c411ed6e847a3e2ebdfeb
        String url = "";
        //获取网络连接对象
        OkHttpClient client = new OkHttpClient();
        //获取请求体
        RequestBody body = new FormBody.Builder().build();
        //获取请求
        Request request = new Request.Builder().post(body).url(url).build();
        //发送请求，获取服务器返回的响应 注意：此方法一定要放到子线程
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            //获取响应中的数据，并转成String
            String data = response.body().string();
            Gson gson = new Gson();
            MyBean myBean = gson.fromJson(data, MyBean.class);
            return myBean;
        } else {
            throw new IllegalAccessError("获取网络数据失败");
        }
    }
}
